package sonics

import (
	"bytes"
	"fmt"
	"github.com/bytedance/sonic"
	"strings"
)

func Sonic() {
	var o1 = map[string]interface{}{
		"a": "b",
	}
	var o2 = 1
	var w = bytes.NewBuffer(nil)
	var enc = sonic.ConfigDefault.NewEncoder(w)
	enc.Encode(o1)
	enc.Encode(o2)
	fmt.Println(w.String())
	// Output:
	// {"a":"b"}
	// 1

	var o = map[string]interface{}{}
	var r = strings.NewReader(`{"a":"b"}{"1":"2"}`)
	var dec = sonic.ConfigDefault.NewDecoder(r)
	dec.Decode(&o)
	dec.Decode(&o)

	fmt.Printf("%+v", o)
	// Output:
	// map[1:2 a:b]
}

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func SonicFromStruct() {
	user := User{Name: "Alice", Age: 25}
	data, err := sonic.Marshal(&user)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data)) // {"name":"Alice","age":25}
}

func SonicToStruct() {
	var user User
	var s string = `{"name":"Bob","age":30}`
	err := sonic.Unmarshal([]byte(s), &user)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v", user) // {Name:Bob Age:30}

	sonic.ConfigDefault.NewDecoder(strings.NewReader(s)).Decode(&user)
	fmt.Printf("%+v", user) // {Name:Bob Age:30}
}
